<template>
  <div class="approval-container">
    <div class="app-title-container title-position">
      <modules-title title-name="创建立项审批" style="margin-bottom: 20px">
        <template slot="btn">
          <el-button plain @click="goBack">返回</el-button>
          <!-- <el-button type="primary" @click="saveForm">保存</el-button> -->
          <el-button type="primary" @click="submitForm">提交 </el-button>
        </template>
      </modules-title>
    </div>
    <div class="main-content-container">
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="small"
        label-width="150px"
      >
        <item-title title="项目概况" />
        <el-row
          :gutter="15"
          class="form-row01"
          style="
            margin-left: 0px;
            margin-right: 0px;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
          "
        >
          <el-form-item
            label="项目来源"
            prop="project_source_id"
            style="width: 50%"
          >
            <el-select
              v-model="formData.project_source_id"
              :disabled="
                (types !== 2 && selfProjectId !== '') ||
                  (types !== 2 && auditProjectId !== '')
              "
              placeholder="请选择项目来源"
              filterable
              clearable
              :style="{ width: '100%' }"
              @change="projectSourceChange"
            >
              <el-option
                v-for="(item, index) in projectSourceOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="fromChange"
            label="自研立项信息"
            :prop="
              formData.project_source_id == '1' ? 'demand_info_id' : 'nomarl'
            "
            style="width: 50%"
          >
            <!-- :disabled="selfProjectId!==''||auditProjectId!==''" -->
            <el-autocomplete
              v-model="formData.demand_info_project_name"
              :fetch-suggestions="requireQuerySearchAsync"
              :disabled="auditProjectId !== ''"
              placeholder="可模糊搜索同意立项未提交立项审批的自研立项项目"
              style="width: 100%"
              @change="selfProjectChange"
              @select="handleSelect"
            >
              <template slot="suffix">
                <el-tooltip
                  content="可模糊搜索同意立项未提交立项审批的自研立项项目"
                  placement="bottom"
                  effect="light"
                >
                  <i class="el-icon-warning" />
                </el-tooltip>
              </template>
              <template slot-scope="{ item }">
                <div class="name">{{ item.project_name }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="项目编号" prop="project_no" style="width: 50%">
            <el-input
              v-model="formData.project_no"
              placeholder="请输入项目编号"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="项目名称" prop="project_name" style="width: 50%">
            <el-input
              v-model="formData.project_name"
              placeholder="请输入申请项目名称"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item
            label="项目类型"
            prop="project_type_id"
            style="width: 50%"
          >
            <el-select
              v-model="formData.project_type_id"
              placeholder="请选择项目类型"
              clearable
              :style="{ width: '100%' }"
              @change="projectTypeChange"
            >
              <el-option
                v-for="(item, index) in projectTypeOptions"
                :key="index"
                :label="item.dict_val"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="申报类别"
            prop="apply_type_id"
            style="width: 50%"
          >
            <el-select
              v-model="formData.apply_type_id"
              placeholder="请选择申报类别"
              clearable
              :style="{ width: '100%' }"
              @change="applyTypeChange"
            >
              <el-option
                v-for="(item, index) in applyTypeOptions"
                :key="index"
                :label="item.dict_val"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药物类别" prop="medical_type" style="width: 50%">
            <el-input
              v-model="formData.medical_type"
              placeholder="请输入药物类别"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item
            label="剂型与规格"
            prop="dosage_norms"
            style="width: 50%"
          >
            <el-input
              v-model="formData.dosage_norms"
              placeholder="请输入剂型与规格"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item
            label="药物成分"
            prop="medical_ingredient"
            style="width: 50%"
          >
            <el-input
              v-model="formData.medical_ingredient"
              placeholder="请输入药物成分"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item
            label="功能主治"
            prop="function_attending"
            style="width: 50%"
          >
            <el-input
              v-model="formData.function_attending"
              placeholder="请输入功能主治"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="用法用量" prop="usage_num" style="width: 50%">
            <el-input
              v-model="formData.usage_num"
              placeholder="请输入用法用量"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="疗程" prop="treatment" style="width: 50%">
            <el-input
              v-model="formData.treatment"
              placeholder="请输入疗程"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item
            label="质量标准来源"
            prop="quality_source"
            style="width: 50%"
          >
            <el-input
              v-model="formData.quality_source"
              type="textarea"
              placeholder="请输入质量标准来源"
              :autosize="{ minRows: 1, maxRows: 2 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="项目目标" prop="project_goal" style="width: 50%">
            <el-input
              v-model="formData.project_goal"
              type="textarea"
              placeholder="请输入项目目标"
              :autosize="{ minRows: 1, maxRows: 2 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
        </el-row>

        <item-title title="项目可行性分析" />

        <el-row :gutter="15" style="margin-left: 0px; margin-right: 0px">
          <el-form-item label="项目优势" prop="project_advantage">
            <el-input
              v-model="formData.project_advantage"
              type="textarea"
              placeholder="请输入项目优势"
              :autosize="{ minRows: 1, maxRows: 2 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="国外研发情况" prop="abroad_research">
            <el-input
              v-model="formData.abroad_research"
              type="textarea"
              placeholder="请输入国外研发情况"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="国内研发情况" prop="internal_research">
            <el-input
              v-model="formData.internal_research"
              type="textarea"
              placeholder="请输入国内研发情况"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="市场分析" prop="market_analysis">
            <el-input
              v-model="formData.market_analysis"
              type="textarea"
              placeholder="请输入市场分析"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <div style="display: flex; justify-content: space-between">
            <el-form-item
              label="临床前支出预算"
              prop="budget_before"
              style="width: 50%; padding-right: 40px"
            >
              <el-input
                v-model="formData.budget_before"
                placeholder="请输入临床前支出预算（元）"
                clearable
                :style="{ width: '100%' }"
              />
            </el-form-item>
            <el-form-item
              label="临床支出预算"
              prop="budget"
              style="width: 50%; padding-left: 40px"
            >
              <el-input
                v-model="formData.budget"
                placeholder="请输入临床支出预算（元）"
                clearable
                :style="{ width: '100%' }"
              />
            </el-form-item>
          </div>
          <el-form-item label="对照药（对照情况）" prop="contrast_medical_info">
            <el-input
              v-model="formData.contrast_medical_info"
              type="textarea"
              placeholder="请输入对照药（对照情况）"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="产权" prop="equity">
            <el-input
              v-model="formData.equity"
              type="textarea"
              placeholder="请输入产权情况"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="15" style="margin-left: 0px; margin-right: 0px">
          <el-form-item label="申请建议" prop="apply_advice">
            <el-input
              v-model="formData.apply_advice"
              type="textarea"
              placeholder="请输入申请建议"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="注意事项" prop="notice">
            <el-input
              v-model="formData.notice"
              type="textarea"
              placeholder="请输入注意事项"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入备注"
              :autosize="{ minRows: 1, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  projectInfoDetail,
  auditDetail,
  submitApproval,
  approvalEdit,
  agreeProjectList
} from '@/api/projectInformation'

export default {
  components: {},
  data() {
    return {
      types: 2, // 判断是否为直接创建立项审批，1，不是；2，是
      formData: {
        demand_info_id: '',
        demand_info_project_name: '',

        demand_idea_id: '',
        demand_idea_name: '',
        project_no: '',
        project_name: '',
        project_source: '自研',
        project_source_id: '1',
        project_type: '',
        project_type_id: '',
        medical_type: '',
        apply_type: '',
        apply_type_id: '',
        function_attending: '',
        dosage_norms: '',
        medical_ingredient: '',
        quality_source: '',

        usage_num: '',
        treatment: '',
        project_goal: '',
        project_advantage: '',
        abroad_research: '',
        internal_research: '',
        market_analysis: '',
        budget_before: '',
        budget: '',
        contrast_medical_info: '',
        equity: '',
        apply_advice: '',
        notice: '',
        remark: ''
      },
      // 编辑
      selfProjectId: '', // 自研立项id
      auditProjectId: '', // 立项审批id
      detailData: null,
      rules: {
        demand_info_id: [
          {
            required: true,
            message: '请输入同意立项未提交立项审批的自研立项项目',
            trigger: 'blur'
          }
        ],
        project_no: [
          {
            required: true,
            message: '请输入项目编号',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        project_name: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        project_source_id: [
          {
            required: true,
            message: '请选择项目来源',
            trigger: 'change'
          }
        ],
        project_type_id: [
          {
            required: true,
            message: '请选择项目类型',
            trigger: 'change'
          }
        ],
        medical_type: [
          {
            required: true,
            message: '请输入药物类别',
            trigger: 'blur'
          }
        ],
        apply_type_id: [
          {
            required: true,
            message: '请选择申报类别',
            trigger: 'change'
          }
        ],
        dosage_norms: [
          {
            required: true,
            message: '请输入剂型与规格',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        medical_ingredient: [
          {
            required: true,
            message: '请输入药物成分',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        function_attending: [
          {
            required: true,
            message: '请输入功能主治',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        usage_num: [
          {
            required: true,
            message: '请输入用法用量',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        treatment: [
          {
            required: true,
            message: '请输入疗程',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        quality_source: [
          {
            required: true,
            message: '请输入质量标准来源',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        project_goal: [
          {
            required: true,
            message: '请输入项目目标',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        project_advantage: [
          {
            required: true,
            message: '请输入项目优势',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        abroad_research: [
          {
            required: true,
            message: '请输入国外研发情况',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        internal_research: [
          {
            required: true,
            message: '请输入国内研发情况',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        market_analysis: [
          {
            required: true,
            message: '请输入市场分析',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        budget_before: [
          {
            required: true,
            message: '请输入临床前支出预算（元）',
            trigger: 'blur'
          },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确额格式,可保留两位小数'
          }
        ],
        budget: [
          {
            required: true,
            message: '请输入临床支出预算（元）',
            trigger: 'blur'
          },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确额格式,可保留两位小数'
          }
        ],
        contrast_medical_info: [
          {
            required: true,
            message: '请输入对照药（对照情况）',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        equity: [
          {
            required: true,
            message: '请输入产权情况',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        apply_advice: [
          {
            required: true,
            message: '请输入申请建议',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        notice: [
          {
            required: true,
            message: '请输入注意事项',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        normal: []
      },
      projectSourceOptions: [
        {
          label: '自研',
          value: '1'
        },
        {
          label: '委托',
          value: '2'
        }
      ],
      projectTypeOptions: [],
      applyTypeOptions: []
    }
  },
  computed: {
    fromChange() {
      let bool = true
      if (this.formData.project_source_id === '1') {
        bool = true
      } else if (this.formData.project_source_id === '2') {
        bool = false
      }
      console.log(bool)
      return bool
    }
  },
  watch: {},
  created() {
    this.getSysAllDic()
    this.types = Number(this.$route.query.types) || 2
    // 通过projectId判断创建与编辑
    this.selfProjectId = this.$route.query.projectId || ''
    this.auditProjectId = this.$route.query.auditProjectId || ''
    if (this.selfProjectId) {
      this.getprojectInfoDetail(this.selfProjectId)
    }
    if (this.auditProjectId) {
      this.getAuditDetail(this.auditProjectId)
    }
  },
  mounted() {},
  methods: {
    goBack() {
      this.$router.back()
    },
    // 项目来源选择改变
    projectSourceChange(val) {
      // elementui的重置只充值了v-model绑定的，id/name不能同时
      this.formData = {
        demand_info_id: '',
        demand_info_project_name: '',

        demand_idea_id: '',
        demand_idea_name: '',
        project_no: '',
        project_name: '',
        project_source: '自研',
        project_source_id: val,
        project_type: '',
        project_type_id: '',
        medical_type: '',
        apply_type: '',
        apply_type_id: '',
        function_attending: '',
        dosage_norms: '',
        medical_ingredient: '',
        quality_source: '',

        usage_num: '',
        treatment: '',
        project_goal: '',
        project_advantage: '',
        abroad_research: '',
        internal_research: '',
        market_analysis: '',
        budget_before: '',
        budget: '',
        contrast_medical_info: '',
        equity: '',
        apply_advice: '',
        notice: '',
        remark: ''
      }
      const obj = this.projectSourceOptions.find((itm) => {
        return itm.value === val
      })
      this.formData.project_source = obj.label
      console.log(this.formData)
      this.$nextTick(() => {
        this.$refs['elForm'].clearValidate([
          'apply_type_id',
          'project_type_id'
        ])
      })
    },
    // 项目类型改变
    projectTypeChange(val) {
      const obj = this.projectTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.project_type = obj.dict_val
      console.log(val, this.formData)
    },
    // 申报类别改变
    applyTypeChange(val) {
      const obj = this.applyTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.apply_type = obj.dict_val
      console.log(val, this.formData)
    },
    selfProjectChange() {
      this.formData = {
        demand_info_id: '',
        demand_info_project_name: '',

        demand_idea_id: '',
        demand_idea_name: '',
        project_no: '',
        project_name: '',
        project_source: '自研',
        project_source_id: '1',
        project_type: '',
        project_type_id: '',
        medical_type: '',
        apply_type: '',
        apply_type_id: '',
        function_attending: '',
        dosage_norms: '',
        medical_ingredient: '',
        quality_source: '',

        usage_num: '',
        treatment: '',
        project_goal: '',
        project_advantage: '',
        abroad_research: '',
        internal_research: '',
        market_analysis: '',
        budget_before: '',
        budget: '',
        contrast_medical_info: '',
        equity: '',
        apply_advice: '',
        notice: '',
        remark: ''
      }
      // 直接重置，只是把v-model绑定的name重置了，他的id还在
      this.$nextTick(() => {
        this.$refs['elForm'].clearValidate([
          'apply_type_id',
          'project_type_id'
        ])
      })
    },
    getSysAllDic() {
      let allDic = this.$store.getters.sysDic()
      if (!allDic) {
        this.$store.dispatch('sys/getSysAllDic').then((data) => {
          allDic = data
        })
      }
      console.log(allDic)
      this.projectTypeOptions = allDic['project_type']
      this.applyTypeOptions = allDic['apply_type']
    },
    // 获取自研立项详情
    getprojectInfoDetail(id) {
      const datas = { id: id }
      projectInfoDetail(datas).then((res) => {
        if (res.code === 200) {
          this.detailData = res.data
          this.formData = {
            ...this.detailData,
            budget_before:
              Number(this.detailData.budget_before) > 0
                ? this.detailData.budget_before
                : '',
            budget:
              Number(this.detailData.budget) > 0 ? this.detailData.budget : '',
            demand_info_id: this.detailData.id,
            demand_info_project_name: this.detailData.project_name
          }
          console.log(this.formData)
        }
      })
    },
    // 获取立项审批详情
    getAuditDetail(id) {
      const datas = { id: id }
      auditDetail(datas).then((res) => {
        if (res.code === 200) {
          this.detailData = res.data
          this.formData = {
            ...this.detailData,
            demand_info_id: this.detailData.id,
            demand_info_project_name: this.detailData.project_name
          }
        }
      })
    },
    // 创建立项审批
    submitApprovalOperation(subdata) {
      subdata.id = ''
      submitApproval(subdata).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '提交成功',
            duration: 1500
          })
          this.$route.params.refresh = true
          this.$router.back()
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
            duration: 1500
          })
        }
      })
    },
    // 编辑立项审批
    editApprovalOperation(subdata) {
      const that = this
      approvalEdit(subdata).then((res) => {
        if (res.code === 200) {
          that.$message({
            type: 'success',
            message: '提交成功',
            duration: 1500,
            onClose: () => {
              that.$route.params.refresh = true
              that.$router.back()
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
            duration: 1500
          })
        }
      })
    },
    submitForm() {
      const that = this
      console.log(this.formData)
      this.$refs.elForm.validate((valid) => {
        if (!valid) return
        // ToDo 提交表单
        var subdata = { ...this.formData }
        // 格式转换
        subdata.budget_before = Number(subdata.budget_before)
        subdata.budget = Number(subdata.budget)
        if (this.selfProjectId) {
          that.submitApprovalOperation(subdata)
        } else if (this.auditProjectId) {
          that.editApprovalOperation(subdata)
        } else {
          that.submitApprovalOperation(subdata)
        }
      })
    },

    // saveForm() {
    //   const that = this
    //   this.$refs['elForm3'].validate((valid) => {
    //     if (!valid) return
    //     // ToDo 提交表单
    //   })
    // },

    // 课题输入联想
    async requireQuerySearchAsync(queryString, cb) {
      const res = await agreeProjectList({ name: queryString })
      var restaurants = res.data || []
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants

      cb(results)
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.project_name
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    handleSelect(item) {
      console.log(item)
      this.$router.replace({
        name: 'submitApproval',
        query: {
          projectId: item.info_id,
          types: this.types,
          t: new Date().getTime()
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/scss/views/projectInfomation/submitApproval/submitApproval.scss";
</style>
